package com.winhxd.b2c.order.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.order.condition.OrderSpuFavoriteEditCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderSpuFavoriteQueryCondition;
import com.winhxd.b2c.common.domain.order.model.OrderSpuFavorite;
import com.winhxd.b2c.common.domain.order.vo.OrderSpuFavoriteVO;
import com.winhxd.b2c.common.domain.product.condition.ProductSpuListCondition;
import com.winhxd.b2c.common.domain.product.vo.ProductSpuSimpleVO;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.product.ProductServiceClient;
import com.winhxd.b2c.order.dao.OrderSpuFavoriteMapper;
import com.winhxd.b2c.order.service.OrderSpuFavoriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收藏夹实现类
 * @author suhaochan
 * @date 2019/1/9 17:22:01
 */
@Service
public class OrderSpuFavoriteServiceImpl implements OrderSpuFavoriteService {

	private static final Logger logger = LoggerFactory.getLogger(OrderSpuFavoriteServiceImpl.class);
	
	@Autowired
	private OrderSpuFavoriteMapper orderSpuFavoriteMapper;
	
	@Autowired
	private ProductServiceClient productServiceClient;
	
	@Override
	public int saveFavorite(OrderSpuFavoriteEditCondition condition) {
		OrderSpuFavorite queryModel = new OrderSpuFavorite();
		queryModel.setCustomerId(condition.getCustomerId());
		queryModel.setSpuId(condition.getSpuId());
		List<OrderSpuFavorite> oldFavorites = orderSpuFavoriteMapper.selectByModel(queryModel);
		Date current = new Date();
		if (!CollectionUtils.isEmpty(oldFavorites)) {
			//更新--如果已经在收藏夹中存在该商品，则更新
			OrderSpuFavorite favoriteUpdate = oldFavorites.get(0);
			//用户针对同一商品可以反复收藏以及取消，即收藏已取消的，取消已收藏的
			Integer newStatus = favoriteUpdate.getStatus()==1?0:1;
			favoriteUpdate.setStatus(newStatus);
			favoriteUpdate.setUpdated(current);
			return orderSpuFavoriteMapper.updateByPrimaryKeySelective(favoriteUpdate);
		} else {
			//新增
			OrderSpuFavorite favoriteInsert = new OrderSpuFavorite();
			favoriteInsert.setCustomerId(condition.getCustomerId());
			favoriteInsert.setSpuId(condition.getSpuId());
			favoriteInsert.setStatus(1);
			favoriteInsert.setCreated(current);
			favoriteInsert.setUpdated(current);
			return orderSpuFavoriteMapper.insertSelective(favoriteInsert);
		}
	}

	@Override
	public int removeFavorite(OrderSpuFavoriteEditCondition condition) {
		OrderSpuFavorite favorite = new OrderSpuFavorite();
		favorite.setId(condition.getFavoriteId());
		favorite.setStatus(0);
		favorite.setUpdated(new Date());
		return orderSpuFavoriteMapper.updateByPrimaryKeySelective(favorite);
	}

	@Override
	public PagedList<OrderSpuFavoriteVO> findFavorite(OrderSpuFavoriteQueryCondition condition) {
		PagedList<OrderSpuFavoriteVO> result = new PagedList<OrderSpuFavoriteVO>();
		result.setPageNo(condition.getPageNo());
		result.setPageSize(condition.getPageSize());
		Page page = PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
		//根据用户ID获取有效的收藏夹列表数据
		OrderSpuFavorite queryModel = new OrderSpuFavorite();
		queryModel.setCustomerId(condition.getCustomerId());
		queryModel.setStatus(1);
		if (condition.getSpuId() != null && condition.getSpuId() != 0) {
			queryModel.setSpuId(condition.getSpuId());
		}
		List<OrderSpuFavorite> favorites = orderSpuFavoriteMapper.selectByModel(queryModel);
		if (CollectionUtils.isEmpty(favorites)) {
			result.setTotalRows(0);
			result.setData(null);
			return result;
		}
		//从收藏夹中获取spuId集合
		List<Long> spuIds = getSpuIdListByFavorite(favorites);
		//根据spuID集合获取收藏夹商品信息
		Map<Long, ProductSpuSimpleVO> favoriteProds = getFavoriteProdBySpuIds(condition.getCustomerId(),spuIds);
		List<OrderSpuFavoriteVO> favoriteVOList = new ArrayList<OrderSpuFavoriteVO>();
		//无库存商品信息统计
		List<OrderSpuFavoriteVO> noStockFavoriteVOList = new ArrayList<OrderSpuFavoriteVO>();
		//下架商品信息统计
		List<OrderSpuFavoriteVO> unSaleFavoriteList = new ArrayList<OrderSpuFavoriteVO>();
		//根据商品服务返回的商品信息组合购物车信息
		for (OrderSpuFavorite favorite : favorites) {
			ProductSpuSimpleVO productSpuSimpleVO = favoriteProds.get(favorite.getSpuId());
			OrderSpuFavoriteVO favoriteVO = new OrderSpuFavoriteVO();
			if (productSpuSimpleVO != null) {
				BeanUtils.copyProperties(productSpuSimpleVO,favoriteVO);
				favoriteVO.setFavoriteId(favorite.getId());
				if (productSpuSimpleVO.getSaleStatus() == 0) {
					//已下架
					unSaleFavoriteList.add(favoriteVO);
				} else if (productSpuSimpleVO.getStockStatus() == 0) {
					//无库存
					noStockFavoriteVOList.add(favoriteVO);
				} else {
					favoriteVOList.add(favoriteVO);
				}
			}
		}
		//无库存/已下架的商品排在最后
		favoriteVOList.addAll(unSaleFavoriteList);
		favoriteVOList.addAll(noStockFavoriteVOList);
		
		result.setData(favoriteVOList);
		result.setTotalRows(page.getTotal());
		return result;
	}

	/**
	 * 
	 * @author suhaochan
	 * @date 2019年1月9日 下午7:06:17 
	 * @Description 根据spuID集合获取收藏夹商品信息
	 * @param 
	 * @return
	 */
	private Map<Long, ProductSpuSimpleVO> getFavoriteProdBySpuIds(Long customerId, List<Long> spuIds) {
		ProductSpuListCondition condition =  new ProductSpuListCondition();
		condition.setCustomerId(customerId);
		condition.setSpuIdList(spuIds);
		ResponseResult<Map<Long, ProductSpuSimpleVO>> result = productServiceClient.findSimpleProductList(condition);
		if (result == null || result.getCode() != BusinessCode.CODE_OK || CollectionUtils.isEmpty(result.getData())) {
			logger.info("OrderSpuFavoriteServiceImpl{} ->getFavoriteProdBySpuIds 商品服务调用获取收藏夹商品信息列表接口失败");
			throw new BusinessException(BusinessCode.CODE_403002);
		}
		return result.getData();
	}

	/**
	 * 
	 * @author suhaochan
	 * @date 2019年1月9日 下午6:12:29 
	 * @Description 从收藏夹中获取spuId集合
	 * @param 
	 * @return
	 */
	private List<Long> getSpuIdListByFavorite(List<OrderSpuFavorite> favorites) {
		List<Long> spuIds = new ArrayList<Long>();
        if (!CollectionUtils.isEmpty(favorites)) {
        	spuIds = favorites.stream()
                    .map(favorite -> favorite.getSpuId()).collect(Collectors.toList());
        }
        return spuIds;
	}

}
